import request from '@/utils/request'

/**
 * 获取会话列表
 * @param {Object} params 分页参数
 * @returns {Promise}
 */
export function getConversationList(params) {
  return request({
    url: '/message/conversations',
    method: 'post',
    data: params
  })
}

/**
 * 获取会话消息列表
 * @param {string} conversationId 会话ID
 * @param {Object} params 分页参数
 * @returns {Promise}
 */
export function getConversationMessages(conversationId, params) {
  console.log(conversationId)
  // 判断conversationId是否为对象类型
  if (typeof conversationId === 'object' && conversationId !== null) {
    // 如果是对象类型，检查id是否存在
    if (!conversationId.id) {
      throw new Error('会话ID不能为空');
    }
    conversationId = conversationId.id;
  }
  return request({
    url: `/message/conversations/${conversationId}/messages`,
    method: 'post',
    data: params
  })
}

/**
 * 发送私信
 * @param {Object} data 消息数据
 * @returns {Promise}
 */
export function sendMessage(data) {
  return request({
    url: '/message/send',
    method: 'post',
    data
  })
}

/**
 * 标记会话为已读
 * @param {string} conversationId 会话ID
 * @returns {Promise}
 */
export function markConversationAsRead(conversationId) {
   console.log('markConversationAsRead', conversationId)
  return request({
    url: `/message/conversations/${conversationId}/read`,
    method: 'post'
  })
}

/**
 * 撤回消息
 * @param {string} messageId 消息ID
 * @returns {Promise}
 */
export function recallMessage(messageId) {
  return request({
    url: `/message/messages/${messageId}/recall`,
    method: 'post'
  })
}

/**
 * 获取未读消息总数
 * @returns {Promise}
 */
export function getUnreadMessageCount() {
  return request({
    url: '/message/unread-count',
    method: 'get'
  })
}

/**
 * 获取或创建与指定用户的会话
 * @param {string} otherUserId 对方用户ID
 * @returns {Promise}
 */
export function getOrCreateConversation(otherUserId) {
  return request({
    url: '/message/conversations/create',
    method: 'post',
    params: { otherUserId }
  })
}
